package com.qzboot.basic.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.qzboot.basic.service.mapper.SysUserRoleMapper;
import com.qzboot.facade.entity.SysUserRole;
import com.qzboot.facade.service.SysUserRoleService;
import com.qzboot.facade.support.CrudServiceImpl;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zengzhihong
 * @date 2019-12-16
 */
@Service
public class SysUserRoleServiceImpl extends CrudServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Override
    public List<Long> listRoleIdByUserId(Long userId) {
        List<SysUserRole> userRoleList = baseMapper.selectList(Wrappers.<SysUserRole>lambdaQuery().select(SysUserRole::getRoleId).eq(SysUserRole::getUserId, userId));
        return userRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveUserRole(Long userId, List<Long> roleIdList) {
        if (ObjectUtil.isNull(userId) || CollectionUtil.isEmpty(roleIdList)) {
            return false;
        }
        baseMapper.delete(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));

        List<SysUserRole> saveList = CollectionUtil.newArrayList();
        for (Long roleId : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            saveList.add(sysUserRole);
        }
        return this.saveBatch(saveList);
    }

    @Override
    public boolean removeByUserId(Long userId) {
        return SqlHelper.retBool(baseMapper.delete(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId)));
    }

    @Override
    public boolean removeByRoleId(Long roleId) {
        return SqlHelper.retBool(baseMapper.delete(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getRoleId, roleId)));
    }
}
